package com.jianyun.jyzs.activity;

import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.support.annotation.NonNull;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.text.TextUtils;
import android.util.Log;
import android.view.View;
import android.view.ViewTreeObserver;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;

import com.hannesdorfmann.mosby3.mvp.MvpActivity;
import com.jianyun.jyzs.R;
import com.jianyun.jyzs.adapter.EngineerRecyAdapter;
import com.jianyun.jyzs.bean.EngProjectLocResult;
import com.jianyun.jyzs.bean.EngineerProjectResult;
import com.jianyun.jyzs.bean.EngineeringResult;
import com.jianyun.jyzs.constant.SysConstant;
import com.jianyun.jyzs.dao.EngProjectDao;
import com.jianyun.jyzs.dao.EngineerDao;
import com.jianyun.jyzs.db.PushEvent;
import com.jianyun.jyzs.presenter.EngieerPresenter;
import com.jianyun.jyzs.utils.LoginCache;
import com.jianyun.jyzs.utils.Utils;
import com.jianyun.jyzs.utils.UtilsStyle;
import com.jianyun.jyzs.view.iview.IEngieerView;
import com.jianyun.jyzs.widget.PasteEditText;
import com.jrmf360.rylib.common.util.ToastUtil;
import com.omadahealth.github.swipyrefreshlayout.library.SwipyRefreshLayout;
import com.omadahealth.github.swipyrefreshlayout.library.SwipyRefreshLayoutDirection;

import java.util.HashMap;
import java.util.List;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;
import com.jianyun.jyzs.utils.RceLog;
import io.rong.eventbus.EventBus;

/**
 * 工程动态
 * Created by yangshijun on 2018/5/30.
 */

public class EngineeringDynamicActivity extends MvpActivity<IEngieerView, EngieerPresenter> implements IEngieerView {

    @BindView(R.id.topBack)
    ImageView topBack;
    @BindView(R.id.iv_search)
    ImageView ivSearch;
    @BindView(R.id.iv_create)
    ImageView ivCreate;
    @BindView(R.id.head)
    LinearLayout head;
    @BindView(R.id.recyclerView)
    RecyclerView recyclerView;
    @BindView(R.id.swipy)
    SwipyRefreshLayout refreshLayout;
    @BindView(R.id.et_sendmessage)
    PasteEditText etSendmessage;
    @BindView(R.id.btn_send)
    Button btnSend;
    @BindView(R.id.ll_toDiscuss)
    LinearLayout llToDiscuss;
    @BindView(R.id.rl_root)
    RelativeLayout rlRoot;

    private EngineerDao dao;
    private String userId;
    private String enterpriseCode;
    private List<EngineeringResult.EngineerBean> engineer;
    private EngineerRecyAdapter adapter;
    public boolean mark = false;
    public String compareId="";
    public String placeName=null;
    public String projectId=null;
    public String proJectName = null;
    public String position = null;

    public  int pageIndex=1;
    public Handler handler = new Handler(){

    };
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        //UtilsStyle.setStatusBarMode(this,true);
        EventBus.getDefault().register(this);
        super.onCreate(savedInstanceState);
        setContentView(R.layout.ac_engineering);
        ButterKnife.bind(this);
        initData();
        initView();
    }

    private void initData() {
        dao = new EngineerDao(this);
        userId = LoginCache.getInstance().getUserInfo().getUserId();
        enterpriseCode = LoginCache.getInstance().getLoginCache().getEnterpriseCode();

        recyclerView.setLayoutManager(new LinearLayoutManager(this));

        adapter = new EngineerRecyAdapter(this, llToDiscuss, etSendmessage);
        adapter.setUserid = userId;
        adapter.enterpriseCode = enterpriseCode;
        recyclerView.setAdapter(adapter);
        setEngineerView();
        getPresenter().getEngineer(dao, userId, enterpriseCode,"1");
    }

    private void initView() {
        EngProjectDao engProjectDao = new EngProjectDao(this);
        HashMap<String, String> hmap = new HashMap<>();
        hmap.put("enterpriseCode", enterpriseCode);
        hmap.put("method", "GetProJectList");
        hmap.put("pageIndex", "1");
       // getPresenter().getP1DataToService(engProjectDao, hmap);
        initInputLinstner();

        refreshLayout.setOnRefreshListener(new SwipyRefreshLayout.OnRefreshListener() {
            @Override
            public void onRefresh(SwipyRefreshLayoutDirection direction) {
                if (direction == SwipyRefreshLayoutDirection.BOTTOM) {
                    //加载更多
                    //compareId=engineer.get(engineer.size()-1).getId();
                    pageIndex++;
                    getPresenter().getRefreshEngineer(dao, userId, enterpriseCode,pageIndex+"");
                   // getPresenter().refeshListData(dao, userId, enterpriseCode, "0",compareId,projectId,placeName);
                } else if (direction == SwipyRefreshLayoutDirection.TOP) {
                    getPresenter().getRefreshEngineer(dao, userId, enterpriseCode,1+"");
                    //刷新
                    //getPresenter().refeshListData(dao, userId, enterpriseCode, "1",compareId,projectId,placeName);

                }
            }
        });
    }

    private void setEngineerView() {
        engineer = dao.getEngineer(enterpriseCode);
        Log.i("test","数据库中："+engineer.size());
        adapter.setList(engineer);
    }

    @NonNull
    @Override
    public EngieerPresenter createPresenter() {
        return new EngieerPresenter();
    }

    @Override
    public void showLoading() {

    }

    @Override
    public void hintLoading() {

    }

    @Override
    public void getEngieerSuccess() {
        setEngineerView();
    }

    @Override
    public void getP1DataSuccess() {

    }


    @Override
    public void refeshSuccess() {
        if (proJectName!=null){
            engineer = dao.getEngineerByTag(proJectName, position);
            adapter.setList(engineer);
        }else {
            setEngineerView();
        }
        refreshLayout.setRefreshing(false);

    }

    @Override
    public void onFailed(String msg) {
        refreshLayout.setRefreshing(false);
    }

    @OnClick({R.id.topBack, R.id.iv_search, R.id.iv_create, R.id.btn_send})
    public void onViewClicked(View view) {
        switch (view.getId()) {
            case R.id.btn_send:
                //发送评论
                String trim = etSendmessage.getText().toString().trim();
                if (!TextUtils.isEmpty(trim)) {
                    adapter.sendDiscuss(trim);
                    etSendmessage.setText(null);
                    Utils.closeKeyBoard(EngineeringDynamicActivity.this, btnSend);
                    llToDiscuss.setVisibility(View.INVISIBLE);
                } else {
                    ToastUtil.showNoWaitToast(EngineeringDynamicActivity.this, "评论不可为空");
                }
                break;
            case R.id.topBack:
                finish();
                break;
            case R.id.iv_create:
                //创建
                startActivityForResult(new Intent(this, CreateEngineerActivity.class), 99);
                break;
            case R.id.iv_search:
                //搜索工程动态
                startActivityForResult(new Intent(this, SelectEProjectActivity.class), 100);
                break;
        }
    }

    public void onEvent(PushEvent event) {
        //收到新增推送更新数据
        final int category = event.getCategory();
        if (category==1){
            handler.post(new Runnable() {
                @Override
                public void run() {
                    Log.i("test","更新数据");
                    setEngineerView();
                }
            });
        }else {
            //更新头部新消息
            handler.post(new Runnable() {
                @Override
                public void run() {
                    Log.i("test","更新头部新消息");
                    adapter.notifyMessageList();
                }
            });

        }

    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        RceLog.d("lml", "requestCode" + requestCode + "resultCode" + resultCode + "data=" + data);
        if (resultCode == -1 & requestCode == 99) {
//            engineer = dao.getEngineer(enterpriseCode);
//            adapter.setList(engineer);
            setEngineerView();
        }
        if (requestCode == 112) {
            adapter.notifyMessageList();
        }
        if (requestCode == 111) {
            //刷新
            setEngineerView();
        }
        if (resultCode == -1 & requestCode == 100 & data != null) {
            EngineerProjectResult.EngProject engProject = (EngineerProjectResult.EngProject) data.getSerializableExtra(SysConstant.msg_p1);
            EngProjectLocResult.EngTypeLocBean locBean = (EngProjectLocResult.EngTypeLocBean) data.getSerializableExtra(SysConstant.msg_p2);
            if (engProject != null) {
                RceLog.d("lml", engProject.toString());
                proJectName = engProject.getProJectName();
                adapter.setProject(engProject);
            }
            if (locBean != null) {
                RceLog.d("lml", locBean.toString());
                position = locBean.getPosition();
                placeName=position;
                adapter.setLocBean(locBean);
            }
            if (engProject != null) {
                if (engProject.isAll()) {
                    refreshLayout.setEnabled(true);
                    int autoId = engProject.getAutoId();
                    projectId=autoId+"";
                    engineer = dao.getEngineer(enterpriseCode);
                    adapter.setList(engineer);
                } else {
                    refreshLayout.setEnabled(true);
                    int autoId = engProject.getAutoId();
                    projectId=autoId+"";
                    engineer = dao.getEngineerByTag(proJectName, position);
                    adapter.setList(engineer);
                }
            }
        }

        if (resultCode==20){
            //删除啊

            setEngineerView();
        }
    }

    //对键盘的监听
    private void initInputLinstner() {

        rlRoot.getViewTreeObserver().addOnGlobalLayoutListener(new ViewTreeObserver.OnGlobalLayoutListener() {
            @Override
            public void onGlobalLayout() {
                //比较Activity根布局与当前布局的大小
                int heightDiff = rlRoot.getRootView().getHeight() - rlRoot.getHeight();
                if (heightDiff > 100) {
                    if (!mark) {
                        llToDiscuss.setVisibility(View.VISIBLE);
                        mark = true;
                    }
                } else {
                    if (mark) {
                        llToDiscuss.setVisibility(View.GONE);
                        adapter.clearArgs();
                        mark = false;
                    }
                }
            }
        });
    }
}
